package util;

import cn.hutool.core.util.StrUtil;
import com.olt.pageConfig.PagePermission;
import com.olt.result.PageResult;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;


import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

//读取页面的XML
public class PageUtil {
   public static final Resource resource = new ClassPathResource("static/page.xml");

   public static List<PagePermission> getPage(List<String> pers,List<String> roles)throws Exception{
       Field[] fields=PagePermission.class.getFields();
       SAXBuilder builder = new SAXBuilder();
       Document document = builder.build(resource.getInputStream());
       Element e=document.getRootElement();
       List<PagePermission> res=new ArrayList<>();
       Queue<Element> queue=  new LinkedList<>(e.getChildren());
       while (!queue.isEmpty()) {
           Element es = queue.remove();
           String per=es.getAttributeValue("permission");
           String role=es.getAttributeValue("role");
           //判断父权限是否存在
           if(!(StrUtil.isEmpty(per)||pers.contains(per))) {
               continue;
           }
           if(!(StrUtil.isEmpty(role)||roles.contains(role))) {
               continue;
           }

           if (es.getChildren().size() > 0) {
               queue.addAll(es.getChildren());
           }
           PagePermission pagePermission = new PagePermission();
           for (Field f : fields) {
               f.set(pagePermission,es.getAttributeValue(f.getName()));
           }
           res.add(pagePermission);

       }
       return res;


   };

   public static<T> void  setPageRes(PageResult<T> pageRes, Page<T> page){
        pageRes.setTotal(page.getTotalElements());
        pageRes.setSize(page.getSize());
        pageRes.setList(page.getContent());
   }

}
